<template>
	<div id="login" >
		<img src="@/assets/image/banner3.png" alt="" class="login_image">
		<div class="login_main" >
			<div class="login_style">
				<!-- <div class="login_logo" :style="{ backgroundImage: `url(${loginlogo})` }"></div> -->
				<div class="login_box" >
				<!-- 账号密码登录 -->
				<div v-if="loginByName">
					<div style="login_box_header">
						<span class="loginByLoginName">账号登录</span>
					</div>
					<el-form style="margin-top:20px;" :model="userForm" :rules="userRuleForm" ref="userRuleForm" class="demo-ruleForm">
						<el-form-item prop="nickName">
							<el-input prefix-icon="el-icon-user" v-model="userForm.nickName"></el-input>
						</el-form-item>
						<el-form-item prop="password">
							<el-input prefix-icon="el-icon-lock" type="password" v-model="userForm.password"></el-input>
						</el-form-item>
						<el-form-item>
							<el-button class="register_button"  type="primary" @click="loginByLoginName('userRuleForm')">立即登录</el-button>
						</el-form-item>
					</el-form>
				</div>
				<!-- 邮箱登录 -->
				<div v-if="loginByEmail" >
					<div style="login_box_header">	
						<span class="loginByLoginName">邮箱登录</span>
					</div>
					<el-form style="margin-top:20px;" :model="userForm" :rules="userRuleForm" ref="userRuleForm" class="mailContent" >
						<el-form-item prop="mail">
							<el-input prefix-icon="el-icon-message" v-model="userForm.mail"></el-input>
						</el-form-item>
						<el-form-item prop="mailCode">
							<el-input  v-model="userForm.mailCode" style="width:36%;float:l	eft;"></el-input>
							<el-button  class="login_mailCode"  @click="getMailCountdown('userRuleForm')" :disabled="mailTotalTime <60">{{mailContent}}</el-button>
						</el-form-item>
						<el-form-item>
							<el-button class="register_button"  type="primary" @click="loginByMaill('userRuleForm')">立即登录</el-button>
						</el-form-item>
					</el-form>
				</div>
				<!-- 手机号登录 -->
				<div v-if="loginByPhone">
					<div style="login_box_header">
						<span class="loginByLoginName">手机号登录</span>
					</div>
					<el-form style="margin-top:20px;" :model="userForm" :rules="userRuleForm" ref="userRuleForm" class="demo-ruleForm">
						<el-form-item prop="phone">
							<el-input prefix-icon="el-icon-phone" v-model="userForm.phone"></el-input>
						</el-form-item>
						<el-form-item prop="phoneCode">
							<el-input  v-model="userForm.phoneCode" style="width:36%;float:left;"></el-input>
							<el-button  class="login_mailCode"  @click="getPhoneCountdown('userRuleForm')" :disabled="phoneTotalTime <60">{{phoneContent}}</el-button>
						</el-form-item>
						<el-form-item>
							<el-button class="register_button"  type="primary" @click="loginByPhones('userRuleForm')">立即登录</el-button>
						</el-form-item>
					</el-form>
				</div>
				<div class="other_logins">
					<span class="login_span">还没有账号？</span>
					<el-link class="register_now" @click="dialogVisible = true">立即注册</el-link>
					<!-- 账号密码登录显示 -->
					<div class="login_method" v-if="loginByName">
						<span class="login_method_register">其他方式登录：</span>
						<i id="phone_number" class="el-icon-phone-outline" @click="loginByPhonePage()"></i>
						<i id="postbox_login" class="el-icon-message" @click="loginByEmailPage()"></i>
					</div>
					<!-- 邮箱登录显示 -->
					<div class="login_method" v-if="loginByEmail">
						<span class="login_method_register">其他方式登录：</span>
						<i id="phone_number" class="el-icon-phone-outline" @click="loginByPhonePage()"></i>
						<i id="postbox_login" class="el-icon-user" @click="loginByNamePage()"></i>
					</div>
					<!-- 手机号登录显示 -->
					<div class="login_method" v-if="loginByPhone">
						<span class="login_method_register">其他方式登录：</span>
						<i id="phone_number" class="el-icon-user" @click="loginByNamePage()"></i>
						<i id="postbox_login" class="el-icon-message" @click="loginByEmailPage()"></i>
					</div>
				</div>
				<!-- 注册弹窗 -->
				<el-dialog title="乐工坊注册账号"	:visible.sync="dialogVisible"	width="30%">
					<el-form :model="registerUserFrom" status-icon :rules="rules" ref="rules" label-width="115px" class="register_content" >
						<el-form-item prop="registerPhone"  label="输入手机号">
						<el-input prefix-icon="el-icon-phone" v-model="registerUserFrom.registerPhone" style="width:70%"></el-input>
						</el-form-item>
						<el-form-item prop="registerPhoneCode" label="输入验证码">
							<el-input  v-model="registerUserFrom.registerPhoneCode" style="width:36%;float:left;"></el-input>
							<el-button  class="login_mailCode"  @click="getRegisterPhoneCountdown('rules')" :disabled="registerPhoneTotalTime <60">{{registerPhoneContent}}</el-button>
						</el-form-item>
						<!-- 操作 -->
						<el-form-item>
							<el-button type="primary" style="width:70%" plain  @click="determineRegister('rules')">确认注册</el-button>
						</el-form-item>
					</el-form>
				</el-dialog>
				<Vcode
				:show="verifyShow"
				@success="success"
				@close="close"
				/>
				</div>
			</div>
			
		</div>
		<!-- 底部 -->
		 <Bottom id="bottom"></Bottom>
	</div>
</template>

<script>
import Vcode from "vue-puzzle-vcode";
import loginbc from '@/assets/image/banner3.png'
import loginlogo from '@/assets/ClassifyImage/柴犬logo.jpg'
// 引入底部组件
import Bottom from '../components/home/Bottom.vue'
export default {
	components:{
      Vcode,
	  Bottom
    },
	data () {
		// 验证验证码
		const comparePhoneCode = (rule , value , callback) => {
			if(value == ''){
				callback(new Error("验证码不能为空"))
			} else {
				this.$axios.get('/userLogin/comparePhoneCode?code=' + value).then(res => {
					if(res.data.data.flag){
						callback();
					} else {
						callback(new Error('验证码不正确'))
					}
				})
			}
		}
		// 校验注册手机号查重
		const checkRegisterPhone = (rule, value, callback) => {
			const mobile = /^(1[3456789]\d{9})$/; 
			if (value == '') {
				callback(new Error('手机号不能为空'))
			} else {
				if(mobile.test(value)){
					this.$axios.get('/userLogin/checkPhone?phone=' + value).then(res => {
						if(res.data.data != null){
							callback(new Error('当前手机号已存在'))
						}else {
							callback();
						}
					})
				} else {
					callback(new Error('输入正确的手机号格式'))
				}
			}
			
		}
		// 验证邮箱号是否正确
		var validateEmail = (rule, value, callback) => {
			const regMobile =  /^([a-zA-Z0-9]+[-_\.]?)+@[a-zA-Z0-9]+\.[a-z]+$/;
			if (value === '') {
				callback(new Error('请正确填写邮箱'));
			} else {
				if (value !== '') { 
					var reg=/^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
					if(!reg.test(value)){
						callback(new Error('请输入有效的邮箱'));
					}
					if(regMobile.test(value)){
						this.$axios.get('/userLogin/checkMail?mail=' + value).then(res => {
							if(res.data.data == null){
								callback(new Error('当前邮箱号未注册'))
							} else {
								callback();
							}
						})
					} else{
						callback(new Error('请输入合法的邮箱'))
					}
				}
			}
		};
		// 验证手机号的规则
		const checkPhone = (rule, value, callback) => {
			let regPone = null
			//手机号
			let mobile = /^(1[3456789]\d{9})$/  
			// 座机
			let tel = /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/ 
			// charAt查找第一个字符方法，用来判断输入的是座机还是手机号
			if (value !== null && value.charAt(0) === '0') { 
				regPone = tel
			} else if (value !== null && value.charAt(0) !== '0') {
				regPone = mobile
			}
			if (regPone === null) {
				return callback(
					new Error('请输入手机号')
				)
			} else if (!regPone.test(value)) {
				return callback(
					new Error("请输入正确的手机号格式")
				)
			} else {
				if(mobile.test(value)){
					this.$axios.get('/userLogin/checkPhone?phone=' + value).then(res => {
						if(res.data.data == null){
							callback(new Error('当前手机号未注册'))
						}else {
							callback();
						}
					})
				} else {
					callback(new Error('输入正确的手机号格式'))
				}
			}
		};
		// 校验登录名字中文
		const checkName = (rule, value, callback) => {
			this.userForm.nickName = value.replace(/[\u4E00-\u9FA5]/g, "");
			if(this.userForm.nickName == ''){
				callback(new Error('账号不允许存在中文'));
			} else {
				callback();
			}
			
		};
		return {
			// 注册弹窗
			dialogVisible: false,
			// 邮箱倒计时默认60秒
			mailTotalTime: 60,
			// 手机号倒计时默认60秒
			phoneTotalTime: 60,
			// 注册手机号倒计时默认60秒
			registerPhoneTotalTime: 60,
			// 邮箱按钮文字
			mailContent: "发送验证码",
			// 手机按钮文字
			phoneContent: "发送验证码",
			// 注册手机按钮文字
			registerPhoneContent: "发送验证码",
			// 手机号登录
			loginByPhone:true,
			// 邮箱登录
			loginByEmail:false,
			// 账号密码登录
			loginByName:false,
			//pc登录页面logo
			loginlogo:loginlogo,
			// pc登录页面背景图片
			loginbc: loginbc, 
			// 验证码状态
			verifyShow: false,
			msg: '',
			// 验证码模态框是否出现
      		isShow: true,
			// 注册用户对象
			registerUserFrom:{
				// 用户昵称
				registerNickName:'',
				// 用户手机号
				registerPhone:'',
				// 用户手机号验证码
				registerPhoneCode:''
			},
			// 用户对象
			userForm: {
				// 用户登录名
				nickName: '',
				// 密码
				password: '',
				// 用户手机号
				phone: '',
				// 用户邮箱
				mail: '',
				// 邮箱验证码
				mailCode: '',
				// 手机号验证码
				phoneCode: ''
			},
			 // 注册校验规则
			rules: {
				registerPhoneCode: [
					{validator: comparePhoneCode, trigger: 'blur'}
				],
				// 校验手机号是否已经存在
				registerPhone: [
					{validator: checkRegisterPhone, trigger: 'blur'}
				],
				// 校验用户名称
				registerNickName: [
					{ required: true, message: '用户名称不能为空', trigger: 'blur' },
				],
			},
			// 校验规则
			userRuleForm: {
				// 校验用户手机号
				phone:[
					 { required: true, validator: checkPhone, trigger: ["blur"] },
				],
				// 校验用户邮箱
				mail: [
					{ required: true, validator: validateEmail, trigger: 'blur' },
				],
				// 校验手机号验证码
				phoneCode: [
					{ required: true, message: '请输入验证码', trigger: 'blur' },
				],
				// 校验邮箱验证码
				mailCode: [
					{ required: true, message: '请输入验证码', trigger: 'blur' },
				],
				// 校验登录名称
				nickName: [
					{ required: true, message: '请输入登录账号', trigger: 'blur' },
					{ validator: checkName, trigger: "change" }
				],
				// 检验登录密码
				password: [
					{ required: true, message: '请输入密码', trigger: 'blur' },
				],
			}
		}
	},
	mounted () {

	},
	methods: {
		// pc端注册用户
		registerUsers(){
			var formdata = new FormData()
			formdata.set('phone', this.registerUserFrom.registerPhone)
			this.$axios.post('/userLogin/registerUsers', formdata).then(res =>{
				if (res.data.data > 0) {
					this.message('恭喜您，注册成功', 'success')
					// var fullPath = window.sessionStorage.getItem('fullPath')
					// this.$router.push({path: fullPath})
					// this.$router.push('/Login')
					this.loginRegisterByPhones()
					this.dialogVisible = false
				}  else {
					this.message('注册失败', 'warning')
				}
			})			
		},
		// 注册时校验注册表单
		determineRegister(rules){
			this.$refs[rules].validate((valid) => {
				if (valid) {
					this.registerUsers()
				} else {
					this.message('完善注册信息', 'warning')
				}
			});
		},
		// pc注册手机号登录
		loginRegisterByPhones(){
			this.$axios({
				method: 'post',
				url: '/userLogin/loginByPhone',
				data: {
					username: this.registerUserFrom.registerPhone,
					code: this.registerUserFrom.registerPhoneCode
				},
				headers: {
					'Content-Type': 'application/x-www-form-urlencoded'
				},
			}).then(res=>{
				if(res.data.flag == true){
					window.sessionStorage.setItem('token', res.data.data.token)
					window.sessionStorage.setItem('userId', res.data.data.userId)
					window.sessionStorage.setItem('avatarUrl', res.data.data.avatarUrl)
					var fullPath = window.sessionStorage.getItem('fullPath')
					this.$router.push({path: fullPath})
				} else{
					window.sessionStorage.removeItem('token')
					this.$message.warning("手机验证码不正确");
					this.userForm.mailCode = ''
				}
			})
		},
		// pc端手机号登录
		loginByPhones(userRuleForm){
			this.$refs[userRuleForm].validate((valid) => {
				if (valid) {
					this.$axios({
						method: 'post',
						url: '/userLogin/loginByPhone',
						data: {
							username: this.userForm.phone,
							code: this.userForm.phoneCode
						},
						headers: {
							'Content-Type': 'application/x-www-form-urlencoded'
						},
					}).then(res=>{
						if(res.data.flag == true){
							window.sessionStorage.setItem('token', res.data.data.token)
							window.sessionStorage.setItem('userId', res.data.data.userId)
							window.sessionStorage.setItem('avatarUrl', res.data.data.avatarUrl)
							var fullPath = window.sessionStorage.getItem('fullPath')
							this.$router.push({path: fullPath})
						} else{
							window.sessionStorage.removeItem('token')
							this.$message.warning("手机验证码不正确");
							this.userForm.mailCode = ''
						}
					})
				}
			});
		},
		// pc端邮箱登录
		loginByMaill(userRuleForm){
			this.$refs[userRuleForm].validate((valid) => {
				if (valid) {
					this.$axios({
						method: 'post',
						url: '/userLogin/loginByMail',
						data: {
							username: this.userForm.mail,
							code: this.userForm.mailCode
						},
						headers: {
							'Content-Type': 'application/x-www-form-urlencoded'
						},
					}).then(res=>{
						if(res.data.flag == true){
							window.sessionStorage.setItem('token', res.data.data.token)
							window.sessionStorage.setItem('userId', res.data.data.userId)
							window.sessionStorage.setItem('avatarUrl', res.data.data.avatarUrl)
							var fullPath = window.sessionStorage.getItem('fullPath')
							this.$router.push({path: fullPath})
						} else{
							window.sessionStorage.removeItem('token')-
							this.$message.warning("邮箱验证码不正确");
							this.userForm.mailCode = ''
						}
					})
				}
			});
		},
		// 向我们的邮箱发送验证码
		loginByMailCode(){
			this.$axios.get('/userLogin/loginByMailCode?mail=' + this.userForm.mail).then(res => {
			})
		},
		// 向我们的手机号发送验证码
		sendPhoneCode(){
			this.$axios.get('/userLogin/sendPhoneCode?phone=' + this.userForm.phone).then(res => {
			})
		},
		//  注册时向我们的手机号发送验证码
		sendRegusterPhoneCode(){
			this.$axios.get('/userLogin/sendPhoneCode?phone=' + this.registerUserFrom.registerPhone).then(res => {
			})
		},
		// 注册手机号验证发送倒计时   
		getRegisterPhoneCountdown(rules) {
			// 校验是否输入手机号 
			this.$refs[rules].validateField('registerPhone', (valid) => {
				if (valid === '') {
					// 发送验证码
					this.sendRegusterPhoneCode()
					// 60秒倒计时
					let clock =  window.setInterval(() => {
						this.registerPhoneContent = this. registerPhoneTotalTime + 's后重新发送';
						this.registerPhoneTotalTime --;
						if(this. registerPhoneTotalTime < 0){
							this. registerPhoneTotalTime = 60;
							this.registerPhoneContent = "重新发送验证码";
							window.clearInterval(clock);
						}
					}, 1000);
				}
			})
		},
		 // 手机号验证发送倒计时   
		getPhoneCountdown(userRuleForm) {
			// 校验是否输入邮箱
			this.$refs[userRuleForm].validateField('phone', (valid) => {
				if (valid === '') {
					// 发送验证码
					this.sendPhoneCode()
					// 60秒倒计时
					let clock =  window.setInterval(() => {
						this.phoneContent = this. phoneTotalTime + 's后重新发送';
						this.phoneTotalTime --;
						if(this. phoneTotalTime < 0){
							this. phoneTotalTime = 60;
							this.phoneContent = "重新发送验证码";
							window.clearInterval(clock);
						}
					}, 1000);
				}
			})
		},
		 // 邮箱验证发送倒计时   
		getMailCountdown(userRuleForm) {
			// 校验是否输入邮箱
			this.$refs[userRuleForm].validateField('mail', (valid) => {
				if (valid === '') {
					// 发送验证码
					this.loginByMailCode()
					// 60秒倒计时
					let clock =  window.setInterval(() => {
						this.mailContent = this. mailTotalTime + 's后重新发送';
						this.mailTotalTime --;
						if(this. mailTotalTime < 0){
							this. mailTotalTime = 60;
							this.mailContent = "重新发送验证码";
							window.clearInterval(clock);
						}
					}, 1000);
				}
			})
		},
		// 跳转注册页面
		registerSkip(){
			this.$router.replace('/Register')
		},
		// 显示账号登录页面
		loginByNamePage(){
			// 手机号登录
			this.loginByPhone = false,
			// 邮箱登录
			this.loginByEmail = false,
			// 账号密码登录
			this.loginByName = true
		},
		// 显示邮箱登录页面
		loginByEmailPage(){
			// 手机号登录
			this.loginByPhone = false,
			// 邮箱登录
			this.loginByEmail = true,
			// 账号密码登录
			this.loginByName = false
		},
		// 显示手机号登录页面
		loginByPhonePage(){
			// 手机号登录
			this.loginByPhone = true,
			// 邮箱登录
			this.loginByEmail = false,
			// 账号密码登录
			this.loginByName = false
		},
		// 用户通过了验证
		success(msg){
			// 通过验证后，需要手动隐藏模态框
			this.verifyShow = false;
			this.$axios({
				method: 'post',
				url: '/userLogin/loginByLoginName',
				data: {
					username:  this.userForm.nickName,
					password:  this.userForm.password,
				},
				headers: {
					'Content-Type': 'application/x-www-form-urlencoded'
				},
			}).then(res=>{
				if(res.data.flag == true){
					window.sessionStorage.setItem('token', res.data.data.token)
					window.sessionStorage.setItem('userId', res.data.data.userId)
					window.sessionStorage.setItem('avatarUrl', res.data.data.avatarUrl)
					// this.$router.replace('/')
					// 获取未登录时用户跳转的路径
					var fullPath = window.sessionStorage.getItem('fullPath')
					this.$router.push({path: fullPath})
				} else{
        			window.sessionStorage.removeItem('token')
					this.$message.warning("账户或者密码不对");
					
				}
			})
		},
		// 用户点击遮罩层，应该关闭模态框
		close(){
			this.verifyShow = false;
		},
		// 根据登录账号登录
		loginByLoginName(formName) {
			this.$refs[formName].validate((valid) => {
			if (valid) {
				this.verifyShow = true
			} else {
				return false;
			}
			});
		},
		resetForm(formName) {
			this.$refs[formName].resetFields();
		},
		//消息提示框
		message(message,type){
			this.$message({
				message:message,
				type: type
			});
		},
	}
}
</script>

<style scoped>、
#bottom{
	flex: 100%;
	height: 10px;
}
#login{
	width :1920px;
	height: 974px;
	background-color: #FFF8F0;
	margin: 0 auto;
	overflow: hidden;
	position: relative;
}
.login_style{
	position: relative;
	top: 20%;
	left: 24%;
	width: 768px;
	height: 402px;
}
.login_image{
	width :100%;
	height: 710px;
	background-color: #FFF8F0;
	margin: 0 auto;
	overflow: hidden;
	position: absolute;
}
.login_main{
	width: 94%;
	height: 700px;
	margin: 0 auto;
	position: relative;
}
.login_logo{
	width: 310px;
	height: 301px;
	float: left;
	padding: 50px;
	margin: 0 auto;
	overflow: hidden;
	background-color: white;
}
.login_box{
	float: left;
	width: 250px;
	height: 300px;
	background-color: white;
	padding: 50px;
	background-color: rgba(255, 255, 255, 0.8);
	border: 1px solid rgba(59, 56, 56, 0.18);
}
.login_box_header{
	width:100%;
	height: 50px;
	text-align: center;
}
.forgot_password{
	margin-left: 180px;
	font-size: 12px;
}
.register_button{
	text-align: center;
	width: 100%;
	margin-top: 14px;
}
.loginByLoginName{
	margin-left: 90px;
}
.other_logins{
	width: 100%;
	height: 88px;
}
.register_now{
	float: left;
	font-size: 12px;
}
.login_span{
	font-size: 12px;
	line-height: 1.45;
	float: left;
	color: rgb(116, 115, 115);
	margin-left: 120px;
}
.login_method{
	width: 100%;
	height: 30px;
	float: left;
	margin-top: 40px;
	text-align: center;
}
.login_method_register{
	font-size: 14px;
	color: rgb(116, 115, 115);
}
#phone_number{
	margin-top: 4px;
}
#postbox_login{
	margin-left: 10px;
	margin-top: 6px;
}
.login_mailCode{
	margin-left: 27px;
	font-size: 12px;
}
.disabled{
	background-color: #ddd;
	border-color: #ddd;
	color:#57a3f3;
	cursor: not-allowed;
}
</style>
